<template>
  <Page class="LoadingMorePage" title="无限加载示例页">
    <LoadingScroller :requestFunction="requestFunction" :pageSize="20">
      <view class="UserItem" v-for="item of dataSource" :key="item.id">
        {{ item.name }}
      </view>
    </LoadingScroller>
  </Page>
</template>
<script lang="ts">
import LoadingScroller from '@/components/LoadingScroller.vue';
import Page from '@/components/page/Page.vue';
import ProjectUtil from '@/utils/ProjectUtil';
import Vue from '@/utils/Vue';

interface IUser {
  id: string | number;
  name: string;
}

interface IData {
  searchKey: string;
  dataSource: IUser[];
}

let instance: any;

export default Vue.extend({
  data(): IData {
    return {
      searchKey: '',
      dataSource: [],
    };
  },

  created() {
    instance = this;
  },

  onLoad(option: any) {
    this.searchKey = option.key;
  },

  components: { Page, LoadingScroller },
  props: {},
  methods: {
    async requestFunction(page: number, pageSize: number) {
      await ProjectUtil.sleep(2000);

      const total = 23;
      const currentPageTotal = Math.min(
        pageSize,
        total - (page - 1) * pageSize
      );
      const res = {
        dataSource: new Array(currentPageTotal).fill(0).map((_, index) => {
          const id = index + (page - 1) * pageSize;
          return {
            id,
            name: `name_${id}_${instance.searchKey}`,
          };
        }),
        total,
      };

      instance.dataSource = instance.dataSource.concat(res.dataSource);
      return res;
    },
  },
});
</script>
<style lang="less" scoped>
.LoadingMorePage {
  .UserItem {
    background: white;
    border-radius: 10px;
    margin: 15px;
    padding: 20px;
  }
}
</style>
